package com.wlyuan.gateway.filter;

import com.wlyuan.gateway.config.BlacklistProperties;
import com.wlyuan.gateway.utils.HttpUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author YuanJie
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class BlacklistFilter implements GlobalFilter, Ordered {
    private final BlacklistProperties blacklistProperties;

    private boolean isBlacklistIp(String ip) {
        return blacklistProperties.getIps().contains(ip);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取客户端ip，判断是否在⿊名单中
        // 从上下⽂中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 从request对象中获取客户端ip
        String clientIp = HttpUtils.getClientIp(request);
        // 拿着clientIp去⿊名单中查询，存在的话就拒绝访问
        if (isBlacklistIp(clientIp)) {
            // 拒绝访问，返回  状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            logger.debug("⿊名单IP,拒绝访问！: {}", clientIp);
            String data = "请求被禁止!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        // 合法请求，放⾏，执⾏后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}